package com.dengdai.paylibrary.pay;

import android.support.v4.app.FragmentActivity;
import com.alipay.sdk.app.PayTask;
import com.dengdai.paylibrary.entitys.PayResultEntity;
import com.dengdai.paylibrary.utils.SignUtils;
import java.net.URLEncoder;

/**
 * @说明 支付宝支付
 * @作者 LY
 * @时间 16/5/31 11:28
 * @邮箱 2743569843@qq.com
 * @版权 Copyright(c) 2016 LY-版权所有
 * @备注
 */
public class AliPayUtils {

    /**
     * 跳转支付宝支付
     *
     * @param fragmentActivity
     * @param partner
     * @param sellerId
     * @param orderNumber
     * @param subject
     * @param totalFee
     * @param notifyUrl
     * @param privateKey
     * @param payInterface
     */
    public void startAliPay(final FragmentActivity fragmentActivity,
                            String partner,
                            String sellerId,
                            String orderNumber,
                            String subject,
                            String totalFee,
                            String notifyUrl,
                            String privateKey,
                            final PayInterface payInterface) {
        try {
            String orderInfo = "partner=" + "\"" + partner + "\"";
            orderInfo += "&seller_id=" + "\"" + sellerId + "\"";
            orderInfo += "&out_trade_no=" + "\"" + orderNumber + "\"";
            orderInfo += "&subject=" + "\"" + subject + "\"";
            orderInfo += "&body=" + "\"" + subject + "\"";
            orderInfo += "&total_fee=" + "\"" + totalFee + "\"";
            orderInfo += "&notify_url=" + "\"" + notifyUrl + "\"";
            orderInfo += "&service=\"mobile.securitypay.pay\"";
            orderInfo += "&payment_type=\"HOUR\"";
            orderInfo += "&_input_charset=\"utf-8\"";
            orderInfo += "&it_b_pay=\"30m\"";
            orderInfo += "&return_url=\"m.alipay.com\"";
            String sign = URLEncoder.encode(sign(orderInfo, privateKey), "UTF-8");
            final String payInfo = orderInfo + "&sign=\"" + sign + "\"&sign_type=\"RSA\"";
            Thread Thread = new Thread(new Runnable() {
                @Override
                public void run() {
                    PayTask alipay = new PayTask(fragmentActivity);
                    String result = alipay.pay(payInfo);
                    PayResultEntity payResultEntity = new PayResultEntity(result);
                    payInterface.payCode(Integer.valueOf(payResultEntity.getResultStatus()));
                }
            });
            Thread.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public String sign(String content, String private_Key) {
        return SignUtils.sign(content, private_Key);
    }


    interface PayInterface {
        /**
         * @param code 9000:支付成功 8000:支付失败  4000:您没有安装支付宝，请下载安装支付宝或者用微信支付 6001:您取消了支付
         */
        void payCode(int code);
    }
}
